package cn.hdu.liang.framework.helper;

import cn.hdu.liang.framework.StringConstant;
import cn.hdu.liang.framework.bean.FormParam;
import cn.hdu.liang.framework.bean.Param;
import cn.hdu.liang.framework.util.CodecUtil;
import cn.hdu.liang.framework.util.StreamUtil;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * 请求助手类
 */
public final class RequestHelper {

    /**
     * 创建请求对象
     */
    public static Param createParam(HttpServletRequest req) throws IOException {
        List<FormParam> formParamList = new ArrayList<>();
        formParamList.addAll(parseParameterNames(req));
        formParamList.addAll(parseInputStream(req));
        return new Param(formParamList);
    }

    private static List<FormParam> parseParameterNames(HttpServletRequest req) {
        List<FormParam> formParamList = new ArrayList<>();
        Enumeration<String> paramNames = req.getParameterNames();
        while(paramNames.hasMoreElements()) {
            String fieldName = paramNames.nextElement();
            String[] fieldValues = req.getParameterValues(fieldName);
            if(ArrayUtils.isNotEmpty(fieldValues)) {
                Object fieldValue;
                if(fieldValues.length == 1) {
                    fieldValue = fieldValues[0];
                } else {
                    StringBuilder sb = new StringBuilder("");
                    for(int i = 0; i < fieldValues.length; i++) {
                        sb.append(fieldValues[i]);
                        if(i != fieldValues.length - 1) {
                            sb.append(StringConstant.SEPARATOR);
                        }
                    }
                    fieldValue = sb.toString();
                }
                formParamList.add(new FormParam(fieldName, fieldValue));
            }
        }
        return formParamList;
    }

    private static List<FormParam> parseInputStream(HttpServletRequest req) throws IOException {
        List<FormParam> formParamList = new ArrayList<>();
        String body = CodecUtil.decodeURL(StreamUtil.getString(req.getInputStream()));
        if(StringUtils.isNotEmpty(body)) {
            String[] kvs = StringUtils.splitByWholeSeparator(body, "&");
            if(ArrayUtils.isNotEmpty(kvs)) {
                for(String kv : kvs) {
                    String[] array = StringUtils.splitByWholeSeparator(kv, "=");
                    if(ArrayUtils.isNotEmpty(array) && array.length == 2) {
                        String fieldName = array[0];
                        String fieldValue = array[1];
                        formParamList.add(new FormParam(fieldName, fieldValue));
                    }
                }
            }
        }
        return formParamList;
    }
}
